from django.db import models
from django.db.models import Sum

from df_user.models import Passport
from df_goods.models import Goods
from db.base_models import BaseModel
from db.base_manager import BaseManager

# Create your models here.


class CartManager(BaseManager):
    # 判断购物车中是否有该商品
    def get_one_cart_info(self, passport_id, goods_id):
        cart_info = self.get_one_object(passport_id=passport_id, goods_id=goods_id)
        return cart_info

    # 添加商品到购物车
    def add_one_cart_info(self, passport_id, goods_id, goods_count):
        cart_info = self.get_one_cart_info(passport_id=passport_id, goods_id=goods_id)
        goods = Goods.objects.get_goods_by_id(goods_id=goods_id)
        # 如果购物车中有该商品,更改商品数目
        if cart_info:
            total_count = cart_info.goods_count + goods_count
            # 判断商品库存
            # 如果库存充足
            if total_count <= goods.goods_stock:
                cart_info.goods_count = total_count
                cart_info.save()

                return True
            # 库存不足
            else:
                return False
        # 如果购物车中没有该商品
        else:
            # 判断库存
            # 库存充足
            if goods_count <= goods.goods_stock:
                # 创建对象
                cart_info = self.create_one_object(passport_id=passport_id, goods_id=goods_id, goods_count=goods_count)
                cart_info.save()
                return True
            # 库存不足
            else:
                return False

    def get_cart_count_by_passport(self, passport_id):
        # 获取购物车中的商品总数
        # select sum(goods_count) form s_cart where passport_id=passport_id
        res_dict = self.filter(passport_id=passport_id).aggregate(Sum('goods_count'))
        # {'goods_count__sum':值}
        # {'goods_count__sum':None}
        res = res_dict['goods_count__sum']
        if res is None:
            res = 0
        return res

    def get_cart_list_by_passport(self, passport_id):
        # 获取购物车内商品列表
        cart_list = self.get_object_list(filters={'passport_id': passport_id})

        return cart_list

    def update_one_cart_info(self, passport_id, goods_id, goods_count):
        # 更新购物车内商品数量  goods_count 是要更新的数量，不是增加的数量
        # 获取购物车内已有的商品数量
        cart_info = self.get_one_cart_info(passport_id=passport_id, goods_id=goods_id)
        # 库存充足
        if goods_count <= cart_info.goods.goods_stock:
            cart_info.goods_count = goods_count
            cart_info.save()
            return True
        # 库存不足
        else:
            return False

    def delete_one_cart_info(self, passport_id, goods_id):
        # 删除数据库，在try...except...中，防止出错
        try:
            cart_info = self.get_one_cart_info(passport_id=passport_id, goods_id=goods_id)
            cart_info.delete()
            return True
        except :
            return False

    # 提交订单时会用到这个方法,通过页面长传来的cart_id 的列表，获取cart列表
    # 通过一个cart_id 的list， 获取一个cart的list
    def get_cart_list_by_cart_id_list(self, cart_id_list):
        '''获取id在cart_id_list中购物车记录'''
        # self.filter(id__in=cart_id_list)
        cart_list = self.get_object_list(filters={'id__in':cart_id_list})
        return cart_list

    # 计算商品的总数目和总价格 并保存
    def get_amount_and_count_by_cart_id_list(self, cart_id_list):
        total_count, total_price = 0,0

        cart_list = self.get_object_list(filters={'id__in': cart_id_list})

        # 遍历计算商品总数和总价格
        for cart_info in cart_list:
            total_count = total_count + cart_info.goods_count
            total_price = total_price + cart_info.goods_count* cart_info.goods.goods_price
        return total_count, total_price


class Cart(BaseModel):
    passport = models.ForeignKey('df_user.Passport', verbose_name='所属用户')
    goods = models.ForeignKey('df_goods.Goods', verbose_name='所属商品')

    goods_count = models.IntegerField(default=0, verbose_name='商品数量')

    objects = CartManager()

    class Meta:
        db_table = 's_cart'